<template>
  <div class="mod-config">
    <el-card class="box-card search-input" shadow="never">
      <el-form  label-width="120px"  size="mini" :model="dataForm">
        <el-row>
          <el-col :span="6">
            <el-form-item label="组件名称：">
              <el-input v-model="dataForm.name" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间：">
              <el-date-picker
                @change="createTimeChange"
                style="width: 100%"
                v-model="createTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="组件状态：">
              <cy-select url="/api/v1/broadcast/config/queue_status/val" :all-option="true" v-model="dataForm.status"></cy-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生效时间：">
              <el-date-picker
                @change="timeChange"
                style="width: 100%"
                v-model="time"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-form-item>
              <el-button type="primary" @click="$refs.CyTable.query(dataForm)">查询</el-button>
              <el-button @click="reset()">重置</el-button>
              <el-button type="primary" @click="addQueue">新增队列</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <live-banner-queue-table
      url="/api/v1/liveBannerQueue/list"
      :max-height="500"
      :showBatchDelete="false"
      :showSelection="false"
      :highlightCurrentRow="true"
      :operationWidth="350"
      :content="pageResult"
      :totalSize="totalSize"
      :columns="filterColumns"
      :showEditOperation="true"
      :showDeleteOperation="true"
      @handleDelete="handleDelete"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @copy="copy"
      ref="CyTable"
    >
    </live-banner-queue-table>
    <el-dialog
      width="50%"
      :title="operationText"
      :visible.sync="dialogVisible"
      @close="editCancel">
      <el-dialog
        width="50%"
        title="banner选择"
        :visible.sync="innerVisible"
        @opened="bannerOpened"
        append-to-body>
        <LiveBannerInfoTable @selectionChange="bannerSelectChange" ref="bannerWindow"></LiveBannerInfoTable>
        <el-row  style="text-align: center;margin-top: 10px">
          <el-col :span="6" :offset="6">
            <el-button size="mini" @click="selectBannerCancel">取消</el-button>
          </el-col>
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="selectBannerDetermine">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-row v-loading="editLoading">
        <el-form  label-width="120px" ref="editDataForm" size="mini" :rules="rules" :model="editDataForm">
          <el-col :span="18">
            <el-form-item label="队列名称：" prop="name">
              <el-input v-model="editDataForm.name" maxlength="20" placeholder="最多可编辑20个字" :disabled="isDisabledEdit" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col v-for="(item,index) in selectBannerData" :key="index">
            <el-col :span="18">
              <el-form-item :label="item.label" :prop="item.prop">
                <el-input disabled v-model="item.value">
                  <el-button v-if="!isDisabledEdit" slot="append" @click="openInnerVisible(item.prop)">选择{{item.prop}}</el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="item.required" :offset="6"></el-col>
            <el-col v-else :span="5" :offset="1">
              <el-button size="mini" v-if="!isDisabledEdit" @click="emptyBanner(item.prop)" v-show="item.value">清空选择</el-button>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上架类型：" prop="type">
              <el-radio-group :disabled="isDisabledEdit" @change="editTypeChange" v-model="editDataForm.type">
                <el-radio :label="0">立即上架</el-radio>
                <el-radio :label="1">定时生效</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="editDataForm.type === 1">
            <el-form-item label="上架时间：" prop="time">
              <el-date-picker
                :disabled="isDisabledEdit"
                v-model="editDataForm.time"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择上架时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10" offset="8" v-if="!isDisabledEdit">
            <el-button size="mini"  @click="editCancel">取消</el-button>
            <el-button size="mini"  type="primary" @click="dataFormSubmit('editDataForm')">保存</el-button>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
  import CySelect from "./component/CySelect";
  import LiveBannerQueueTable from "./component/LiveBannerQueueTable";
  import LiveBannerInfoTable from "./component/LiveBannerInfoTable";
  export default {
    components: {
      CySelect,
      LiveBannerQueueTable,
      LiveBannerInfoTable,
    },
    data() {
      return {
        loading: false,
        moreBtnDisable: true,
        currentSelectBanner:'',
        isDisabledEdit: true,
        // 选择banner
        selectBannerData:[
          {
            label:'banner1：',
            prop:'banner1',
            required:true,
            value:''
          },
          {
            label:'banner2：',
            prop:'banner2',
            required:true,
            value:''
          },
          {
            label:'banner3：',
            prop:'banner3',
            required:true,
            value:''
          },
          {
            label:'banner4：',
            prop:'banner4',
            required:false,
            value:''
          },
          {
            label:'banner5：',
            prop:'banner5',
            required:false,
            value:''
          },
          {
            label:'banner6：',
            prop:'banner6',
            required:false,
            value:''
          },
          {
            label:'banner7：',
            prop:'banner7',
            required:false,
            value:''
          },
          {
            label:'banner8：',
            prop:'banner8',
            required:false,
            value:''
          }
        ],
        createTime: [],
        time: [],
        dataForm: {},
        editDataForm: {
          type: 0
        },
        columns: [],
        filterColumns: [],
        bannerList: [],
        pageRequest: {pageNum: 1, pageSize: 10},
        pageResult: [],
        totalSize: 0,
        operationText: '新增队列',
        dialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        countNumForm: {
          allShopNum: '',
          onlineNum: '',
          offlineNum: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListSelections: [],
        invoiceUpdateVisible: true,
        innerVisible: false,
        bannerSelectData: [],
        rules: {
          name: [
            {required: true, message: '请填写队列名称', trigger: 'blur'}
          ],
          banner1: [
            { validator: (rule, value, callback) => {
                if(this.selectBannerData[0].id){
                  callback();
                } else {
                  callback(new Error("请选择banner1"));
                }
              }, trigger: 'blur'}
          ],
          banner2: [
            { validator: (rule, value, callback) => {
                if(this.selectBannerData[1].id){
                  callback();
                } else {
                  callback(new Error("请选择banner2"));
                }
              }, trigger: 'blur'}
          ],
          banner3: [
            { validator: (rule, value, callback) => {
                if(this.selectBannerData[2].id){
                  callback();
                } else {
                  callback(new Error("请选择banner3"));
                }
              }, trigger: 'blur'}
          ],
          time: [{
            validator: (rule, value, callback) => {
              if (this.editDataForm.type === 1) {
                if (value) {
                  value =new Date(Date.parse(value.replace(/-/g, "/")));
                  this.utils.request.liveRequest({
                    url: '/api/v1/liveHomeInfo/getServiceTime',
                    method: 'get',
                  }).then(result => {
                    let data = result.data;
                    if (data.code == '0') {
                      //防止点击此刻获取服务延迟导致不可用 + 1分钟
                      if((value.getTime()+1000*60)<data.data){
                        callback(new Error('生效时间不能小于当前时间'));
                      }
                      callback();
                    }
                    callback();
                  })
                } else {
                  callback(new Error("请选择上架时间"));
                }
              } else {
                callback();
              }
            }, trigger: "blur"
          }]
        },
      }
    },
    mounted: function () {
      this.columns = [
        {prop: "id", label: "队列编号", minWidth: 120},
        {prop: "name", label: "组件名称", minWidth: 120},
        {prop: "type", label: "上架类型", minWidth: 120,formatter:function (row, column, cellValue, index) {
            if (cellValue == 0) {
              return "立即上架";
            } else if (cellValue == 1) {
              return "定时生效";
            }
            return "";
          }},
        {prop: "time", label: "生效时间", minWidth: 120},
        {prop: "status", label: "状态", minWidth: 120,formatter:function (row, column, cellValue, index) {
            if (cellValue == 10) {
              return "进行中";
            } else if (cellValue == 11) {
              return "待生效";
            } else if (cellValue == 12) {
              return "已取消";
            } else if (cellValue == 13) {
              return "已失效";
            } else if (cellValue == 14) {
              return "待发布";
            }
            return "";
          }},
        {prop: "createTime", label: "创建时间", minWidth: 120},
        {prop: "updateTime", label: "修改时间", minWidth: 120},
      ];
      let temp = [];
      this.columns.forEach(function (key, val) {
        temp.push(key);
      });
      this.filterColumns = temp;
    },
    methods: {
      isExists(id){
        let bannerList = this.selectBannerData;
        let b=false;
        if(bannerList&&bannerList.length>0){
          for (let i = 0; i < bannerList.length; i++) {
            if(id==bannerList[i].id){
              b=true;
            }
          }
        }
        return b;
      },
      // 获取数据列表
      findPage() {
        this.$refs.CyTable.findPage(this.dataForm);
      },
      //重置
      reset() {
        this.dataForm = {};
        this.$refs.CyTable.resetForm(this.dataForm);
      },
      // 显示编辑界面
      handleEdit: function (params) {
        this.dialogVisible = true;
        if(params.type == 'edit'){
          this.operationText = '编辑队列';
          this.isDisabledEdit = false
        } else if(params.type == 'detail'){
          this.operationText = '查看队列';
          this.isDisabledEdit = true
        }
        let param = {
          id: params.row.id
        }
        let this_ = this
        this.utils.request.liveRequest({
          url: '/api/v1/liveBannerQueue/getInfo',
          method: 'get',
          params: param
        }).then(result => {
          let data = result.data
          this_.editDataForm = data.data
          let bannerList = this_.editDataForm.liveQueueBannerRequestList;
          if(bannerList&&bannerList.length>0){
            for (let i = 0; i < bannerList.length; i++) {
              this_.selectBannerData[i].id = bannerList[i].bannerId
              this_.selectBannerData[i].value = bannerList[i].bannerName
            }
          }
          this_.$nextTick(() => {
            if (this_.$refs['editDataForm'] !== undefined) {
              this_.$refs['editDataForm'].clearValidate();
            }
          });
        })
      },
      // 显示编辑界面
      addQueue() {
        this.operationText = '新增队列';
        this.dialogVisible = true;
        this.isDisabledEdit = false
      },
      // 删除
      handleDelete: function (params) {
        let ids = params.params;
        let delDataForm = [];
        ids.forEach(val => {
          delDataForm.push(val)
        })
        if (delDataForm.length > 0) {
          let this_ = this;
          this.utils.request.liveRequest({
            url: '/api/v1/liveBannerQueue/batchDelete',
            method: 'post',
            params: delDataForm
          }).then(result => {
            let data = result.data;
            if (data.code === '0') {
              this_.$refs.CyTable.findPage(this_.dataForm)
              this_.$forceUpdate();
              this.$message({message: "操作成功", type: "success"});
            }
          })
        } else {
          this.$message({message: "请选择需要删除的数据", type: "info"});
        }

      },
      // 创建日期改变
      createTimeChange: function (val) {
        if (val) {
          this.dataForm.createTimeStart = val[0]
          this.dataForm.createTimeEnd = val[1]
        } else {
          this.dataForm.createTimeStart = ''
          this.dataForm.createTimeEnd = ''
        }
      },
      // 生效日期改变
      timeChange: function (val) {
        if (val) {
          this.dataForm.timeStart = val[0]
          this.dataForm.timeEnd = val[1]
        } else {
          this.dataForm.timeStart = ''
          this.dataForm.timeEnd = ''
        }
      },
      editTypeChange(val) {
        if (this.editDataForm.type == 0) {
          this.editDataForm.time = ''
        }
      },
      // 编辑取消
      editCancel() {
        this.dialogVisible = false
        this.editDataForm = {
          type: 0
        }
        this.selectBannerData =[
          {
            label:'banner1：',
            prop:'banner1',
            required:true,
            value:''
          },
          {
            label:'banner2：',
            prop:'banner2',
            required:true,
            value:''
          },
          {
            label:'banner3：',
            prop:'banner3',
            required:true,
            value:''
          },
          {
            label:'banner4：',
            prop:'banner4',
            required:false,
            value:''
          },
          {
            label:'banner5：',
            prop:'banner5',
            required:false,
            value:''
          },
          {
            label:'banner6：',
            prop:'banner6',
            required:false,
            value:''
          },
          {
            label:'banner7：',
            prop:'banner7',
            required:false,
            value:''
          },
          {
            label:'banner8：',
            prop:'banner8',
            required:false,
            value:''
          }
        ]
      },
      // 新增提交
      dataFormSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.editDataForm.type==0){
              this.$confirm("确定要立即生效此项列表吗？", "提示", {
                type: "warning"
              })
                .then(() => {
                  this.save()
                })
            } else {
              this.save()
            }
          } else {
            return false;
          }
        });
      },
      // 保存
      save(){
        this.editLoading=true;
        let this_ = this;
        let liveQueueBannerRequestList = []
        this.selectBannerData.forEach(item=>{
          let bannerId = item.id
          if(bannerId){
            liveQueueBannerRequestList.push({
              bannerId:bannerId
            })
          }
        })
        this.editDataForm.liveQueueBannerRequestList = liveQueueBannerRequestList
        this.utils.request.liveRequest({
          url: '/api/v1/liveBannerQueue/save',
          method: 'Post',
          params: this.editDataForm
        }).then(result => {
          this_.dialogVisible = false
          this_.editDataForm = {
            type: 0
          }
          let data = result.data;
          if (data.code === '0') {
            this_.$refs.CyTable.findPage(this_.dataForm)
            this_.$forceUpdate();
            this.$message({message: "操作成功", type: "success"});
          }
          this.editLoading=false;
        })
      },
      // 打开选择banner窗口
      openInnerVisible(name) {
        this.currentSelectBanner = name
        this.innerVisible = true;
      },
      selectBannerCancel() {
        this.innerVisible = false;
      },
      // banner选择确定
      selectBannerDetermine() {
        if(this.bannerSelectData){
          this.selectBannerData.forEach(item=>{
            if(item.prop === this.currentSelectBanner){
              item.value = this.bannerSelectData.name
              item.id = this.bannerSelectData.id
            }
          })
          this.$refs['editDataForm'].clearValidate();
          this.selectBannerCancel()
        } else {
          this.$message({message: "未选择数据列", type: "info"});
        }
      },
      // banner窗口打开后回调
      bannerOpened() {
        this.$refs.bannerWindow.refresh()
      },
      bannerSelectChange(selection) {
        this.bannerSelectData = selection
      },
      // 清空选择
      emptyBanner(prop){
        this.selectBannerData.forEach(item=>{
          if(item.prop === prop){
            item.value = ''
            item.id = ''
          }
        })
      },
      // 复制
      copy(row){
        this.dialogVisible = true;
        this.operationText = '新建队列';
        this.isDisabledEdit = false
        let param = {
          id: row.id
        }
        let this_ = this
        this.utils.request.liveRequest({
          url: '/api/v1/liveBannerQueue/getInfo',
          method: 'get',
          params: param
        }).then(result => {
          let data = result.data
          this_.editDataForm = data.data
          this_.editDataForm.id = null
          this_.editDataForm.time = ''
          let bannerList = this_.editDataForm.liveQueueBannerRequestList;
          if(bannerList&&bannerList.length>0){
            for (let i = 0; i < bannerList.length; i++) {
              this_.selectBannerData[i].id = bannerList[i].bannerId
              this_.selectBannerData[i].value = bannerList[i].bannerName
            }
          }
          this_.$nextTick(() => {
            if (this_.$refs['editDataForm'] !== undefined) {
              this_.$refs['editDataForm'].clearValidate();
            }
          });
        })
      }
    }
  }
</script>
<style scoped lang="scss">

</style>
